import store from "@/store";

const appStore = {
  'oppo': 'com.oppo.market',
  'vivo': 'com.bbk.appstore',
  'meizu': 'com.meizu.mstore',
  'xiaomi': 'com.xiaomi.market',
  'redmi': 'com.xiaomi.market',
  'huawei': 'com.huawei.appmarket',
  'honor': 'com.huawei.appmarket',
  '360': 'com.qihoo.appstore',
  'yingyongbao': 'com.tencent.android.qqdownloader',
}

export default {
  hasAndroidAppStoreInstalledWithMinePackage() {
    const main = plus.android.runtimeMainActivity();
    const packageName = plus.android.invoke(main, 'getPackageName');
    return this.hasAndroidAppStoreInstalled(packageName)
  },
  hasAndroidAppStoreInstalled(packageName) {
    const brand = store.getters.systemInfo.deviceBrand
    const appStorePackageName = appStore[brand]
    const list = []
    if (appStorePackageName) {
      list.push(appStorePackageName)
    }

    list.push(appStore['yingyongbao'])
    list.push(appStore['360'])

    const main = plus.android.runtimeMainActivity();
    const Uri = plus.android.importClass("android.net.Uri");
    const uri = Uri.parse("market://details?id=" + packageName);

    for (let i = 0; i < list.length; i++) {
      const packageName = list[i]
      const Intent = plus.android.importClass('android.content.Intent');
      const intent = new Intent(Intent.ACTION_VIEW, uri);
      intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK;
      intent.setPackage(packageName);
      if (intent.resolveActivity(main.getPackageManager()) !== null) {
        return packageName
      }
    }
  },
  openAndroidAppStore(packageName) {
    const Uri = plus.android.importClass("android.net.Uri");
    const uri = Uri.parse("market://details?id=" + packageName);

    const brand = store.getters.systemInfo.deviceBrand
    const appStorePackageName = appStore[brand] || appStore['yingyongbao']
    if (!this.openAndroidApp(uri, appStorePackageName)) {
      this.openAndroidApp(uri, appStore['360'])
    }

    // console.log(packageName, uri)
  },

  openAndroidApp(uri, packageName = null) {
    const main = plus.android.runtimeMainActivity();
    const Intent = plus.android.importClass('android.content.Intent');
    const intent = new Intent(Intent.ACTION_VIEW, uri);
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK;
    if (packageName) {
      intent.setPackage(packageName);
    }

    if (intent.resolveActivity(main.getPackageManager()) !== null) {
      main.startActivity(intent);
      return true
    }
    return false
  },

  openAndroidAppStoreWithMinePackage() {
    const main = plus.android.runtimeMainActivity();
    const packageName = plus.android.invoke(main, 'getPackageName');
    this.openAndroidAppStore(packageName)
  },

  openIosAppStore() {
    const appid = '1662432981'
    plus.runtime.openURL(`itms-apps://itunes.apple.com/cn/app/id${appid}?mt=8`);
  }
}
